package cc.sunni.rabbitmq.task;

import cc.sunni.rabbitmq.config.Constants;
import cc.sunni.rabbitmq.dao.MqMessageDao;
import cc.sunni.rabbitmq.entity.MqMessage;
import cc.sunni.rabbitmq.entity.Order;
import cc.sunni.rabbitmq.producer.OrderSender;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class RetTryMessageTask {

    @Autowired
    private OrderSender orderSender;
    @Autowired
    private MqMessageDao mqMessageDao;

    @Scheduled(initialDelay = 3000, fixedDelay = 10000)
    public void reSend() {
        log.info("------定时任务开始------");
        // pull status =0 and timeout message
        List<MqMessage> list = mqMessageDao.queryByStatusAndTimeoutMessage();
        list.forEach(mqMessage -> {
            if (mqMessage.getTryCount() >= Constants.MAX_RETRY_COUNT) {
                // update fail message
                mqMessage.setStatus(Constants.MESSAGE_FAILURE);
                mqMessageDao.updateById(mqMessage);
            } else {
                // retry count +1
                mqMessageDao.update4Resend(mqMessage.getMessageId());
                Order order = JSONUtil.toBean(mqMessage.getMessage(), Order.class);
                orderSender.sendOrder(order);
            }
        });
    }
}
